import ExpenseBaseModel from './ExpenseBaseModel.js';
import { formatPaymentDate } from '../../date.js';
import { strToFloat } from 'math.js';  
import Radio from 'backbone.radio';

const ExpenseKmModel = ExpenseBaseModel.extend({
    defaults: {
        type: 'km',
        category: null,
        ht: null,
        start: "",
        end: "",
        description: "",
        customer_id: null,
        project_id: null,
        business_id: null,
        create_return: false,
    },
    initialize(options) {
        if ((options['altdate'] === undefined) && (options['date'] !== undefined)) {
            this.set('altdate', formatPaymentDate(options['date']));
        }
        this.config = Radio.channel('config');
    },
    validation: {
        type_id: {
            required: true,
            msg: "est requis"
        },
        date: {
            required: true,
            pattern: /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/,
            msg: "est requise"
        },
        km: {
            required: true,
            pattern: "amount3",
        },
    },
    getIndice() {
        /*
         *  Return the indice used for compensation of km fees
         */
        let type = this.getType();
        if (type === undefined) {
            return 0;
        } else {
            return strToFloat(type.get('amount'));
        }
    },
    getHT() {
        return strToFloat(this.get('ht'));
    },
    getTva() {
        return 0;
    },
    total() {
        return this.getHT()
    },
    getKm() {
        return strToFloat(this.get('km'));
    },
    instantiateReturnLine() {
        const kwargs = {
            // Invert start/end
            start: this.get('end'),
            end: this.get('start'),
            // Do not loop
            create_return: false,
        };
        // Copy the others
        const keysToCopy = [
            "km",
            "category",
            "date",
            "ht",
            "tva",
            "customer_id",
            "project_id",
            "business_id",
            "description",
            "type_id",
        ];
        keysToCopy.forEach(
            key => kwargs[key] = this.get(key)
        );
        return new ExpenseKmModel(kwargs);
    },
});
export default ExpenseKmModel;
